package com.sun.androidexerciseproject.function.activity;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.NotificationManagerCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.alipay.sdk.app.PayTask;
import com.sun.androidexerciseproject.function.R;
import com.sun.androidexerciseproject.function.base.BaseActivity;
import com.sun.androidexerciseproject.function.data.TestDao;
import com.sun.androidexerciseproject.function.http.HttpRequest;
import com.sun.androidexerciseproject.function.model.BaseClass;
import com.sun.androidexerciseproject.function.model.greendao.MsgModel;
import com.sun.androidexerciseproject.function.service.NotificationMonitorService;
import com.sun.androidexerciseproject.function.test.InterfaceTest;
import com.sun.androidexerciseproject.function.util.LogUtil;
import com.sun.androidexerciseproject.function.util.NetworkUtil;
import com.sun.androidexerciseproject.function.util.greendao.MsgModelDaoUtils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.Callable;

import pub.devrel.easypermissions.EasyPermissions;

/**
 * @author Administrator
 */
public class FirstActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {
    private static final String TAG = "FirstActivity";
    private static final int SDK_PAY_FLAG = 100;
    private static final String JSOUP_STR = "<sysmsg type=\"paymsg\">\n" +
            "        <paymsg>\n" +
            "            <PayMsgType>9</PayMsgType>\n" +
            "        \n" +
            "            <transid><![CDATA[lEI-cFen2Lag1dmbvJWpq64t8fTD2OwSEeotsWmRiwaWGNmR4we6x8gzrBNJwwxjOLwEPn4wnrw0otjyrOMYardUHMVXOaL4pAcmYn2XCaFZnLg05l9DypZ6THgdKsE1]]></transid>\n" +
            "    \t\t\n" +
            "    \t\t\n" +
            "            <username><![CDATA[sjwycying]]></username>\n" +
            "    \t\t\n" +
            "    \t\t\n" +
            "            <displayname><![CDATA[天山潼妈么么琦]]></displayname>\n" +
            "    \t\t\n" +
            "            <timestamp>1572323133</timestamp>\n" +
            "            <fee>1</fee>\n" +
            "            <feetype>1</feetype>\n" +
            "    \n" +
            "    <expire_voice_timestamp><![CDATA[1572323733]]></expire_voice_timestamp>\n" +
            "    <type>wx_f2f</type>\n" +
            "            <scene>0</scene>\n" +
            "            <status>1</status>\n" +
            "    <outtradeno>sScnTCDsSLHSI3CP85P3dsZS268Qe_go3LUhLg-YHj6ymWFbD853sHCZYrip1dPcAlDCQMXF2Rfj7vMUIUkBzA</outtradeno>\n" +
            "        \n" +
            "        </paymsg>\n" +
            "    </sysmsg>";
    private Button mStartBtn;
    private TestDao mTestDao;
    private Handler mHandler = new Handler();
    private int mTest = 0;
    private CountDownTimer mTimer = new CountDownTimer(10000, 1000) {
        String url = "https://www.036buy.com/detail/check.php";

        @Override
        public void onTick(long millisUntilFinished) {
            HttpRequest.getRequest(url);
        }

        @Override
        public void onFinish() {

        }
    };
    private MsgModelDaoUtils msgModelDaoUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        initViews();
        checkPermission();
        String ip = NetworkUtil.getIp(this);
        // 判断是否开启监听通知权限
        if (NotificationManagerCompat.getEnabledListenerPackages(this).contains(getPackageName())) {
            Intent serviceIntent = new Intent(this, NotificationMonitorService.class);
            startService(serviceIntent);
        } else {
            startActivity(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"));
        }
        msgModelDaoUtils = new MsgModelDaoUtils(this);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_first;
    }

    private void randomTest() {
        Random random = new Random();
        int intNumb = random.nextInt(1000000000 - 100000000) + 100000000;
        for (int i = 0; i < 10; i++) {
            intNumb = random.nextInt(20 - 10) + 10;
            System.out.println("intNumb1 " + intNumb);
        }
        SecureRandom secureRandom = new SecureRandom();
        for (int i = 0; i < 10; i++) {
            intNumb = secureRandom.nextInt(20 - 10) + 10;
            System.out.println("intNumb2 " + intNumb);
        }
    }

    private void checkPermission() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
        if (!EasyPermissions.hasPermissions(this, perms)) {
            EasyPermissions.requestPermissions(this, "need storage permisson", 0, perms);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //把申请权限的回调交由EasyPermissions处理
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    //下面两个方法是实现EasyPermissions的EasyPermissions.PermissionCallbacks接口
    //分别返回授权成功和失败的权限
    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        Log.i(TAG, "获取成功的权限" + perms);
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        Log.i(TAG, "获取失败的权限" + perms);
    }

    private void initViews() {
        mStartBtn = (Button) findViewById(R.id.btn_start);
        LogUtil.log("thread Id = " + Thread.currentThread().getId());
        mStartBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int hashcode = hashCode();
                LogUtil.log("hashcode " + hashcode);
                String hash = Integer.toHexString(hashcode);
                LogUtil.log("hash " + hash);
//                String name = AndroidSystemServiceRegistry.getSystemServiceName(AccessibilityManager.class);
//                LogUtil.log("name = " + name);
//                AndroidSystemServiceRegistry.getSystemService(name);
                //add ping duo duo
//                String url = "https://mobile.yangkeduo.com/friend_pay.html?_wv=41729&_wvx=10&fp_id=Z7IXTh2vFhU_tcfpYwZ9m2lBEta5O7QRcyPwRy3qVCs&refer_share_id=MNkJxOcgLHXgDpZ58E26DbuNzmCJq6xb&refer_share_uid=5762817983662&refer_share_channel=message";
//                Uri uri = Uri.parse(url);
//
//                String query = uri.getQuery();
//                LogUtil.log("query = " + query);
//                Set<String> list = uri.getQueryParameterNames();
//                for (String temp : list) {
//                    String value = uri.getQueryParameter(temp);
//                    LogUtil.log("value = " + value);
//
//                }
//                alipayTest();
                //wechat 代付
                //                String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx32e4d3446c02b4b5&redirect_uri=https%3A%2F%2Fpay.m.jd.com%2Fpay%2Fother-pay.html%3FappId%3Djd_android_app4%26payId%3Ddae8d40a9ff7458aa1d335cbaef191fd&response_type=code&scope=snsapi_base&state=123#wechat_redirect&resourceType=jdapp_share&resourceValue=Wxfriends&utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=Wxfriends";
//                shareToFriend(url);
//                int test = testMethod(11);
//                LogUtil.log("onClick test = " + test);

                //                jsoupTest();
//                SecondActivity.startActivity(FirstActivity.this
//                        , 300);
//                mHandler.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        TestLogUtil.log("run thread Id = " + Thread.currentThread().getId());
//                    }
//                });
//                httpTest();
//                callMuliAsyTask();
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        long threadId = Thread.currentThread().getId();
//                        TestLogUtil.log("call Runnable threadId1 = " + threadId);
//                        mHandler.post(new Runnable() {
//                            @Override
//                            public void run() {
//
//                                long threadId = Thread.currentThread().getId();
//                                TestLogUtil.log("call Runnable threadId2 = " + threadId);
//                            }
//                        });
//                    }
//                }).start();
//                SecondActivity.startActivity(FirstActivity.this, -1);

//                getLocalVersion(FirstActivity.this);
//                randomTest();
//                Pattern pattern = Pattern.compile("\\d{20}");
//                Matcher matcher = pattern.matcher("11111111112222222222");
//                boolean ret = matcher.matches();
//                System.out.println("ret = " + ret);
//
//                LogReport.getInstance().upload(getApplicationContext());
            }
        });
//        JsonTest jsonTest = new JsonTest();
//        jsonTest.jsonTest();


//        mTestDao = new TestDao(this);
//        if (!mTestDao.isDataExist()) {
//            mTestDao.init();
//        }
    }

    private void shareToFriend(String url) {
        Intent intent = new Intent();
        ComponentName comp = new ComponentName("com.tencent.mm",
                "com.tencent.mm.ui.tools.ShareImgUI");
        intent.setComponent(comp);
        intent.setAction("android.intent.action.SEND");
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, url);
        startActivity(intent);
    }

    public void getLocalVersion(Context ctx) {
        try {
            PackageInfo packageInfo = ctx.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo("com.eg.android.AlipayGphone", 0);
            int localVersion = packageInfo.versionCode;
            String versionName = packageInfo.versionName;
            LogUtil.log("localVersion = " + localVersion + " versionName = " + versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void test(BaseClass baseClass) {
        baseClass.method();
    }

    private void looper() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                mTest = 0;
                System.out.println("looper begin");
                while (true) {
                    System.out.println("looper mTest = " + mTest);
                    mTest++;
                    if (mTest == 100) {
                        System.out.println("looper mTest = " + mTest);
                        mTest = 0;
                        return;
                    }
                }
            }
        }).start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        LogUtil.log("onActivityResult FirstActivity requestCode " + requestCode + " resultCode " + resultCode);
        super.onActivityResult(requestCode, resultCode, data);
    }


    /**
     * 打开支付宝
     *
     * @param view
     */
    public void openAliPay(View view) {
        try {
            PackageManager packageManager = getPackageManager();
            Intent intent = packageManager.getLaunchIntentForPackage("com.eg.android.AlipayGphone");
            startActivity(intent);
        } catch (Exception e) {
            String url = "https://ds.alipay.com/?from-mobileweb";
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(url));
            startActivity(intent);
        }
    }

    private void callMuliAsyTask() {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        List<Callable<SelfClass>> tasks = new ArrayList<>();
        tasks.add(new CallableAnsyTask(arr, 1));
        tasks.add(new CallableAnsyTask(arr, 2));
        tasks.add(new CallableAnsyTask(arr, 3));
    }

    private void reflectTest() {
        System.out.println("reflectTest");
        InterfaceTest interfaceTest = new InterfaceTest() {
            @Override
            public void method1() {

            }

            @Override
            public void method2() {

            }
        };
        //载入类
        try {
            Context otherPackageContext = this.createPackageContext("com.sunshine.androidjavapractise", Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);
            Class clazz = otherPackageContext.getClassLoader().loadClass("com.sunshine.androidjavapractise.util.StringUtil");
            Method method = clazz.getMethod("getTrimString", String.class);
            String test = (String) method.invoke(null, " hello test ");
            System.out.println("reflectTest test =" + test);
        } catch (ClassNotFoundException e) {
            System.out.println("reflectTest ClassNotFoundException");
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            System.out.println("reflectTest NoSuchMethodException");
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            System.out.println("reflectTest IllegalAccessException");
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            System.out.println("reflectTest InvocationTargetException");
            e.printStackTrace();
        } catch (PackageManager.NameNotFoundException e) {
            System.out.println("reflectTest NameNotFoundException");

        }
    }

    private void yunshanfuTest() {
        //encrypt
        try {
            Context otherPackageContext = this.createPackageContext("com.pay.sdk3.jft.a", Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);
            System.out.println("1111");
            Class clazz = otherPackageContext.getClassLoader().loadClass("sdk.pay.utils.PayLogUtil");
            System.out.println("2222");
            Method method = clazz.getDeclaredMethod("logBase", String.class);
            System.out.println("34444");
            method.setAccessible(true);
            String encryStr = (String) method.invoke(null, "testtest");
            System.out.println("yunshanfuTest encryStr =" + encryStr);
        } catch (ClassNotFoundException e) {
            System.out.println("yunshanfuTest ClassNotFoundException");
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            System.out.println("yunshanfuTest NoSuchMethodException");
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            System.out.println("yunshanfuTest IllegalAccessException");
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            System.out.println("yunshanfuTest InvocationTargetException");
            e.printStackTrace();
        } catch (PackageManager.NameNotFoundException e) {
            System.out.println("yunshanfuTest NameNotFoundException");

        }

    }

    /**
     * Jsoup 解析html练习
     */
    private void jsoupTest() {
        Document document = Jsoup.parse(JSOUP_STR);
        Elements elements = document.getElementsByTag("paymsg");
        for (Element element : elements) {
            String transid = element.select("transid").text().trim();
            LogUtil.log("element transid = " + transid);
            String username = element.select("username").text().trim();
            LogUtil.log("element username = " + username);
            String displayname = element.select("displayname").text().trim();
            LogUtil.log("element displayname = " + displayname);
            String outtradeno = element.select("outtradeno").text().trim();
            LogUtil.log("element outtradeno = " + outtradeno);
            String timestamp = element.select("timestamp").text().trim();
            LogUtil.log("element timestamp = " + timestamp);
            String fee = element.select("fee").text().trim();
            LogUtil.log("element fee = " + fee);
            String test = element.select("test").text().trim();
            LogUtil.log("element test = " + test);
        }
    }

    /**
     * result 格式
     * {
     * "memo" : "xxxxx",
     * "result" : "{
     * \"alipay_trade_app_pay_response\":{
     * \"code\":\"10000\",
     * \"msg\":\"Success\",
     * \"app_id\":\"2014072300007148\",
     * \"out_trade_no\":\"081622560194853\",
     * \"trade_no\":\"2016081621001004400236957647\",
     * \"total_amount\":\"0.01\",
     * \"seller_id\":\"2088702849871851\",
     * \"charset\":\"utf-8\",
     * \"timestamp\":\"2016-10-11 17:43:36\"
     * },
     * \"sign\":\"NGfStJf3i3ooWBuCDIQSumOpaGBcQz+aoAqyGh3W6EqA/gmyPYwLJ2REFijY9XPTApI9YglZyMw+ZMhd3kb0mh4RAXMrb6mekX4Zu8Nf6geOwIa9kLOnw0IMCjxi4abDIfXhxrXyj********\",
     * \"sign_type\":\"RSA2\"
     * }",
     * "resultStatus" : "9000"
     * }
     */
    private void alipayTest() {
        final String orderInfo = "NGfStJf3i3ooWBuCDIQSumOpaGBcQz";   // 订单信息
        LogUtil.log("alipayTest");

        //要在子线程
        Runnable payRunnable = () -> {
            PayTask alipay = new PayTask(FirstActivity.this);
            Map<String, String> result =
                    alipay.payV2(orderInfo, true);
            Message msg = new Message();
            msg.what = SDK_PAY_FLAG;    //SDK_PAY_FLAG此为静态常量，在Activity中声明即可。
            //private static final int SDK_PAY_FLAG = 1;
            msg.obj = result;
            mHandler.sendMessage(msg);
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    public void okGoTest(View view) {
    }

    public void daoInsert(View view) {
        if (null != msgModelDaoUtils) {
            msgModelDaoUtils.insertMsgModel(new MsgModel(1L, "zhangsan"));
            msgModelDaoUtils.insertMsgModel(new MsgModel(2L, "lisi"));
        }
    }

    public void daoGet(View view) {
        if (null != msgModelDaoUtils) {
            List<MsgModel> msgModels = msgModelDaoUtils.queryAllMsgModel();
            if (null != msgModels) {
                Iterator<MsgModel> iterator = msgModels.iterator();
                while ((iterator.hasNext())) {
                    MsgModel msgModel = iterator.next();
                    LogUtil.log("daoGet userName = " + msgModel.getUserName() + ",id = " + msgModel.getId());
                }
            }
        }
    }

    private static class SelfClass {
        Long time;
        int index;

        @Override
        public String toString() {
            return "SelfClass{" +
                    "time=" + time +
                    ", index=" + index +
                    '}';
        }
    }

    public class RunnableAsynTask implements Runnable {

        // 耗时的操作（配置低一些的机器小心CPU 100％，反应慢）
        public void needSomeTime() {
            int len = 50000;
            String[] intArray = new String[len];
            Random random = new Random(len);

            // 初始化数组
            for (int i = 0; i < len; i++) {
                intArray[i] = String.valueOf(random.nextInt());
            }

            // 排序
            Arrays.sort(intArray);
        }

        @Override
        public void run() {
            long startTime = System.currentTimeMillis();
            needSomeTime();
            long endTime = System.currentTimeMillis();
            System.out.println("执行任务耗时：" + (endTime - startTime));
        }
    }

    /**
     * 阿里订单支付
     */

    public class CallableAnsyTask implements Callable<SelfClass> {

        private int[] _arr;
        private int index;

        public CallableAnsyTask(int[] arr, int index) {
            _arr = arr;
            this.index = index;
        }

        @Override
        public SelfClass call() throws Exception {
            long threadId = Thread.currentThread().getId();
            LogUtil.log("call threadId = " + threadId);
            long startTime = System.currentTimeMillis();
            long result = 0;
            for (long j = 0; j < 50000000L; j++) {
                for (int i = 0; i < _arr.length; i++) {
                    result += _arr[i];
                }
            }
            SelfClass selfClass = new SelfClass();
            selfClass.index = this.index;
            long endTime = System.currentTimeMillis();
            selfClass.time = (endTime - startTime) / 1000;
            return selfClass;
        }
    }
}


